package cmd

import (
	"context"

	"gitee.com/linxing_3/sr-core/config"
	"gitee.com/linxing_3/sr-core/config/source"
	"gitee.com/mkwchecking/sr-admin/apps/devtools/adapter/cmd/domain"
	"gitee.com/mkwchecking/sr-admin/apps/devtools/adapter/cmd/table"
	"gitee.com/mkwchecking/sr-admin/apps/devtools/adapter/wire"
	"gitee.com/mkwchecking/sr-admin/apps/devtools/conf"
	"gitee.com/mkwchecking/sr-admin/apps/devtools/entity"
	"gitee.com/mkwchecking/sr-admin/apps/devtools/service"
	"gitee.com/mkwchecking/sr-admin/cmd"
	"gitee.com/mkwchecking/sr-admin/pkg/plugins/pdatabase"
	"github.com/spf13/cobra"
)

var devtoolsCmd = &cobra.Command{
	Use:   "devtools",
	Short: "devtools [table/domain] [add/list/del/...]",
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Help()
	},
}

func init() {
	devtoolsCmd.AddCommand(table.GetTableCmd(serviceGetter))
	devtoolsCmd.AddCommand(domain.GetDomainCmd(serviceGetter))

	cmd.RootCmd().AddCommand(devtoolsCmd)
}

var _devtoolsService *service.DevtoolsSvc

func serviceGetter(cfg string) (*service.DevtoolsSvc, error) {
	if _devtoolsService != nil {
		return _devtoolsService, nil
	}

	src, err := source.New(source.WithCfgFile(cfg))
	if err != nil {
		return nil, err
	}

	if err = src.Scan(config.Get()); err != nil {
		return nil, err
	}
	config.Get().Log.WriteOut = "null"

	conf.SetupConfig(src)
	// _, err = relay.GetConstructor().Install(context.Background(), config.Get())

	ds, err := pdatabase.UpsertDatabase()
	if err != nil {
		return nil, err
	}

	if err := entity.AutoMigrate(ds); err != nil {
		return nil, err
	}

	_devtoolsService, err = wire.NewDevtoolsSvc(context.Background())
	return _devtoolsService, err
}
